package com.googlecode.dgwt.client.dijit.form.base;

import com.google.gwt.i18n.client.BidiUtils;
import com.google.gwt.i18n.client.HasDirection;
import com.googlecode.dgwt.client.dijit.Dijit;
import com.googlecode.dgwt.client.dijit.form.FormWidget;
import com.googlecode.dgwt.client.dojo.Dojo;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class FormValueWidget extends FormWidget implements HasDirection {

    private String invalidMessage = "";
    
    
    protected FormValueWidget(boolean ready) {
        super(ready);
    }

    public String getValue() {
        Object value = getProperty(DOM_PROPERTY, "value");
        return value == null ? "" : "" + value;
    }
    
    public void setValue(String value) {
        setProperty(DOM_PROPERTY, "value", value);
    }
    
    protected String format(String text) {
        return text;
    }

    protected String unformat(String text) {
        return text;
    }

    @Override
    public String getText() {
        return unformat(getValue());
    }

    
    @Override
    public void setText(String text) {
        setValue(format(text));
    }

    @Override
    public Direction getDirection() {
        return BidiUtils.getDirectionOnElement(getAttachedElement("inputElement"));
    }
    
    @Override
    public void setDirection(Direction direction) {
        BidiUtils.setDirectionOnElement(getAttachedElement("inputElement"), direction);
    }
    
    public String getInvalidMessage() {
        return invalidMessage;
    }

    public void setInvalidMessage(String invalidMessage) {
        if (invalidMessage == null) {
            invalidMessage = "";
        }
        this.invalidMessage = invalidMessage;
    }
    
    protected String getDisplayInvalidMessage() {
        if (invalidMessage.isEmpty()) {
            return Dijit.MESSAGE_RESOURCES.valueInvalid(getValue(), getDisplayLabel());
        }
        return Dojo.string.propertiesSubstitute(invalidMessage, getValue(), getDisplayLabel());
    }

}
